import { token_alia } from '@/global.config'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Layout',
      redirect: '/home',
      component: () => import('../views/Layout.vue'),
      children: [
        {
          path: 'home',
          name: 'Home',
          component: () => import('../views/Home.vue')
        },
        {
          path: '/question',
          name: 'Question',
          component: () => import('../views/Question.vue')
        },
        {
          path: '/author',
          name: 'Author',
          component: () => import('../views/Author.vue')
        },
        {
          path: '/answer',
          name: 'Answer',
          component: () => import('../views/Answer.vue')
        },
        {
          path: '/receiver',
          name: 'Receiver',
          component: () => import('../views/Receiver.vue'),
          meta: {
            active: '/home'
          }
        },
        {
          path: '/notify',
          name: 'Notify',
          component: () => import('../views/Notify.vue'),
          meta: {
            active: '/home'
          }
        },
        {
          path: '/author/question',
          name: 'AuthorQuestion',
          component: () => import('../views/AuthorQuestion.vue'),
          meta: {
            active: '/author',
            type: 'author'
          }
        },
        {
          path: '/answer/question',
          name: 'AnswerQuestion',
          component: () => import('../views/AuthorQuestion.vue'),
          meta: {
            active: '/answer',
            type: 'answer'
          }
        },
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/Login.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem(token_alia)
  const exclude = ['/login']
  if (token) {
    exclude.includes(to.path) ? next('/') : next()
  } else {
    if (exclude.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
